package com.grandbroad.eim.ui.activities;

import android.graphics.Color;
import android.os.Bundle;
import android.support.v7.widget.Toolbar;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.easy.west.westclient.Constants;
import com.easy.west.westclient.util.UUIDGenerator;
import com.google.gson.Gson;
import com.grandbroad.eim.R;
import com.grandbroad.eim.app.MyApplication;
import com.grandbroad.eim.base.BaseActivity;
import com.grandbroad.eim.entry.OrderBean;
import com.grandbroad.eim.entry.PayBean;
import com.grandbroad.eim.entry.PaySuccessBean;
import com.grandbroad.eim.utils.UiUtlis;
import com.grandbroad.eim.wxapi.WXPayEntryActivity;
import com.tencent.mm.opensdk.modelmsg.SendAuth;
import com.tencent.mm.opensdk.modelpay.PayReq;
import com.tencent.mm.opensdk.openapi.IWXAPI;
import com.tencent.mm.opensdk.openapi.WXAPIFactory;

import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;
import org.xutils.common.Callback;
import org.xutils.http.RequestParams;
import org.xutils.x;

import java.util.Iterator;
import java.util.Map;
import java.util.Random;
import java.util.Set;
import java.util.SortedMap;

import butterknife.BindView;
import butterknife.ButterKnife;
import dev.utils.LogPrintUtils;
import dev.utils.common.encrypt.MD5Utils;

/**
 * 支付订单界面
 */
public class PayActivity extends BaseActivity {

    @BindView(R.id.img_back_btn)
    ImageView imgBackBtn;
    @BindView(R.id.tv_toolbar_title)
    TextView tvToolbarTitle;
    @BindView(R.id.tool_bar)
    Toolbar toolBar;
    @BindView(R.id.tv_order_des)
    TextView tvOrderDes;
    @BindView(R.id.tv_order_pay)
    TextView tvOrderPay;
    @BindView(R.id.check_pay_wechat)
    CheckBox checkPayWechat;
    @BindView(R.id.li_wechat)
    LinearLayout liWechat;
    @BindView(R.id.btn_pay_now)
    Button btnPayNow;
    private OrderBean orderBean;
    private String order;
    private PayBean payBean;
    private String order_url = Constants.BASE_URL + "pay/wxpay";

    @Override
    protected void initview() {
        toolBar.setBackgroundColor(Color.WHITE);
        tvToolbarTitle.setText("支付订单");
        tvOrderDes.setText("订单描述:" + orderBean.getDescription());
        tvOrderPay.setText("订单金额:" + orderBean.getTotalAmount() + "元");
        setBackBtn(imgBackBtn);
        btnPayNow.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                showProgessDialog("订单生成中");
                //请求后台生成预订单
                getOrder();
            }
        });
    }

    /**
     * 订单申请
     */
    private void getOrder() {
        final RequestParams params = new RequestParams(order_url);
        params.addBodyParameter("totalAmount", "1");
        params.addBodyParameter("orderNum", orderBean.getOrderNum());
        params.addBodyParameter("description", "鼹鼠直播vip \n\t\t\t\t\t\t\t\t\t" + orderBean.getDescription());
        x.http().post(params, new Callback.CommonCallback<String>() {
            @Override
            public void onSuccess(String result) {
                PayBean payBean = new Gson().fromJson(result, PayBean.class);
                dissmissDialog();
                /*
                Bundle bundle = new Bundle();
                bundle.putSerializable("bean",payBean);
                startActivityWithBundle(WXPayEntryActivity.class,false,bundle);
                */
                /**
                 * 开始支付
                 */
                pay(payBean);

            }

            @Override
            public void onError(Throwable ex, boolean isOnCallback) {
                LogPrintUtils.d(ex.getLocalizedMessage());
            }

            @Override
            public void onCancelled(CancelledException cex) {

            }

            @Override
            public void onFinished() {

            }
        });
    }

    /**
     * 跳转微信支付
     *
     * @param payBean
     */
    private void pay(PayBean payBean) {
        IWXAPI mApi = WXAPIFactory.createWXAPI(this, MyApplication.WX_ID);
        mApi.registerApp(MyApplication.WX_ID);

        if (mApi != null && mApi.isWXAppInstalled()) {
            //创建实体
            PayReq payReq = new PayReq();
            payReq.appId = payBean.getData().getAppId();
            payReq.nonceStr = payBean.getData().getNonceStr();
            payReq.sign = payBean.getData().getPaySign();
            payReq.signType = payBean.getData().getSignType();
            payReq.partnerId = payBean.getData().getMchId();
            payReq.prepayId = payBean.getData().getPrepayId();
            payReq.timeStamp = payBean.getData().getTimeStamp();
            payReq.packageValue = "Sign=WXPay";
            mApi.sendReq(payReq);
        } else {
            Toast.makeText(this, "用户未安装微信", Toast.LENGTH_SHORT).show();
        }
    }

    @Override
    protected void initdata() {
        orderBean = (OrderBean) getIntent().getExtras().getSerializable("bean");
        //生成订单号
        String uuid_order = getRandomString(25);
        orderBean.setOrderNum(uuid_order);


    }
    @Override
    protected int setlayout() {
        return R.layout.activity_pay;
    }

    /**
     * 随机生成订单号
     * @param length
     * @return
     */
    public static String getRandomString(int length) { //length表示生成字符串的长度
        String base = "abcdefghijklmnopqrstuvwxyz0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ";
        Random random = new Random();
        StringBuffer sb = new StringBuffer();
        for (int i = 0; i < length; i++) {
            int number = random.nextInt(base.length());
            sb.append(base.charAt(number));
        }
        return sb.toString();
    }

    /**
     * 接收支付回执
     * @param eva
     */
    @Subscribe(threadMode = ThreadMode.MAIN)
    public void getPayResult(PaySuccessBean eva)
    {
        if (eva.isPay())
        {
           dissmissDialog();
        }
        else
        {
            dissmissDialog();
        }
    }
}
